import * as React from 'react'
import { createRoot } from 'react-dom/client'
import { ConfigProvider } from 'antd'
import zh_CN from 'antd/lib/locale/zh_CN'
import Layout from './layout'
import { LocationListener } from 'history'
import { dispatch, getState, history, TabItem } from './store'
import { MenuKey, menu_map, route_list } from './menu'
import { pathname2params } from './utils/common'

const root = createRoot(document.getElementById('app'))
const App = () => {
    return (
        <ConfigProvider locale={zh_CN}>
            <Layout />
        </ConfigProvider>
    )
}

root.render(<App />)

const historyChange: LocationListener<TabItem> = ({ pathname }) => {
    const { tabs } = getState()
    const tab = tabs.find(t => t.pathname === pathname)

    if (!tab) {
        let matched = false
        for (let i = 0; i < route_list.length; i++) {
            const route = route_list[i];
            if (route.component) {
                const params = pathname2params(route.key)(pathname)
                if (params) {
                    matched = true
                    dispatch(state => ({ ...state, tabs: state.tabs.concat({
                        menuKey: route.key,
                        title: route.title,
                        params, pathname,
                    }), pathname }))
                    return
                }
            }
        }
        /** 根路径不处理 */
        if (/\w/.test(pathname) && !matched) {
            const item_404 = menu_map.get(MenuKey.PAGE_404)
            dispatch(state => ({ ...state, tabs: state.tabs.concat({
                menuKey: MenuKey.PAGE_404,
                title: item_404.title,
                pathname,
            }) }))
            return
        }
    }
    dispatch(state => ({ ...state, pathname }))
}
history.listen(historyChange)
if (/\w/.test(history.location.pathname)) {
    historyChange(history.location, null)
} else {
    const { tabs, pathname } = getState()
    if (tabs.length) {
        const last = tabs[tabs.length - 1]
        history.replace(pathname || last.pathname)
    }
}